import * as tools from './helps';
import * as thirdQuery from './third-query.js';

/**
 * 数据表数据加载类，为加载数据表提供统计接口
 * @param {String} dataId 数据ID
 */
const SheetLoader = function(dataId) {
  this.dataId = dataId; // 数据ID
  this.dataInfo = null; // 数据元信息
  this.data = null; // 数据
};

/**
 * 获取数据表元数据信息
 */
SheetLoader.prototype.getDataInfo = async function() {
  return new Promise((resolve, reject) => {
    if (this.dataInfo) {
      resolve(this.dataInfo);
    } else {
      window.api.datav.findAppById({ id: this.dataId }).then(res => {
        this.dataInfo = res.data;
        resolve(res.data);
      });
    }
  });
};

/**
 * 获取数据表数据
 */
SheetLoader.prototype.getData = async function() {
  return new Promise((resolve, reject) => {
    if (this.data) {
      resolve(this.data);
    } else {
      this.getDataInfo()
        .then(res => {
          let loader = SheetLoader.LOADERS[res.typeId];
          return loader.getData(this.dataInfo);
        })
        .then(res => {
          this.data = res;
          resolve(res);
        });
    }
  });
};

/**
 * 获取数据表分页数据
 * @param {Number} pageIndex 分页索引
 * @param {Number} pageSize 分页大小
 */
SheetLoader.prototype.getPagedData = async function(pageIndex, pageSize) {
  return new Promise((resolve, reject) => {
    this.getData().then(res => {
      let pagedData = tools.getArrayPagedData(res, pageIndex, pageSize);
      resolve(pagedData);
    });
  });
};

/**
 * 本地数据数据加载器
 */
const nativeSheetLoader = {
  async getData(dataInfo) {
    return new Promise((resolve, reject) => {
      const data = JSON.parse(dataInfo.data);
      resolve(data);
    });
  },
};

/**
 * 关系型数据数据加载器
 */
const relateSheetLoader = {
  async getData(dataInfo) {
    const shema = JSON.parse(dataInfo.data);
    const response = await window.api.ETL.queryTable(shema);
    return response.data;
  },
};

/**
 * 云盘数据加载器
 */
const cloudSheetLoader = {
  async getData(dataInfo) {
    return new Promise((resolve, reject) => {
      resolve([]);
    });
  },
};

/**
 * 三方服务加载器
 */
const thirdSheetLoader = {
  async getData(dataInfo) {
    return new Promise((resolve, reject) => {
      const sheetData = JSON.parse(dataInfo.data);
      const type = {
        async GET() {
          const response = await thirdQuery.get(sheetData.requestUrl, sheetData.params);
          resolve(response.data.data);
        },
        async POST() {
          const response = await thirdQuery.post(
            sheetData.resType,
            sheetData.requestUrl,
            sheetData.params
          );
          resolve(response.data.data);
        },
      };
      type[sheetData.type].call(this);
    });
  },
};

/**
 * 加载器列表
 */
SheetLoader.LOADERS = {
  '92101': nativeSheetLoader,
  '92102': nativeSheetLoader,
  '92103': nativeSheetLoader,
  '92200': relateSheetLoader,
  '92300': cloudSheetLoader,
  '92400': thirdSheetLoader,
};

export default SheetLoader;
